using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

//TODO add saveable encryption

namespace UA_Dorm_Ethernet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            niApp.Text = GetAllIPAddresses();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            //ValidUAIP();

            if (txtUsername.Text.Replace(" ", "").Length < 2)
            {
                txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Your UAnet ID appears to be incorrect." + Environment.NewLine + txtOutput.Text;
                MessageBox.Show("Your UAnet ID appears to be incorrect.");
                niApp.Icon = new System.Drawing.Icon(@"icon_disconnect.ico");
                return;
            }
            if (txtPassword.Text.Length < 6)
            {
                txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Your UAnet ID appears to be incorrect." + Environment.NewLine + txtOutput.Text;
                MessageBox.Show("Your Password appears to be incorrect.");
                niApp.Icon = new System.Drawing.Icon(@"icon_disconnect.ico");
                return;
            }
            
            //txtOutput.Text = "https://" + txtUsername.Text + ":" + txtPassword.Text + "@gozips.uakron.edu/zid/user/connect.cgi";

            if (PingTest("www.uakron.edu")) // if passes try web test else not error
            {
                if (!WebTest("www.google.com")) //if doesnt pass attempt login else error
                {
                    if (Login(txtUsername.Text, txtPassword.Text)) //if successful start timer
                    {
                        txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Login successful/still connected. Autoconnect feature started." + Environment.NewLine + txtOutput.Text;
                        tmrAttempt.Enabled = true;
                        tmrAttempt.Start();
                        niApp.Icon = new System.Drawing.Icon(@"icon_connect.ico");
                    }
                    else //else stop timer
                    {
                        //MessageBox.Show("Login failed");
                        txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Login Failed." + Environment.NewLine + txtOutput.Text;
                        tmrAttempt.Enabled = false;
                        tmrAttempt.Stop();
                        niApp.Icon = new System.Drawing.Icon(@"icon_disconnect.ico");
                    }
                }
                else
                {
                    //MessageBox.Show("All ready connected.");
                    txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Already connected." + Environment.NewLine + txtOutput.Text;
                    tmrAttempt.Enabled = true;
                    tmrAttempt.Start();
                    niApp.Icon = new System.Drawing.Icon(@"icon_connect.ico");
                }
            }
            else
                MessageBox.Show("WARNING: Can't ping even with the following IPs. \n\n" + GetAllIPAddresses());
        }

        private bool Login(string Username, string Password)
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = "wget.exe";
            proc.StartInfo.Arguments = "https://" + Username + ":" + Password + "@gozips.uakron.edu/zid/user/connect.cgi -o lastlog.log --no-check-certificate --spider";
            proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            try 
            { 
                proc.Start();
                proc.WaitForExit(); //this keeps it from reading the previous log of wget.
                StreamReader srOutput = File.OpenText("lastlog.log");
                string read = null;
                //txtOutput.Text = "";
                while ((read = srOutput.ReadLine()) != null)
                {
                    //txtOutput.Text += read;
                    if (read.Contains("Authorization failed."))
                    {
                        srOutput.Close();
                        txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] UAnet ID and/or Password are incorrect." + Environment.NewLine + txtOutput.Text;
                        MessageBox.Show("UAnet ID and/or Password are incorrect.");
                        niApp.Icon = new System.Drawing.Icon(@"icon_disconnect.ico");
                        return false;
                    }
                    //if no route error
                    if (read.Contains("No route to host."))
                    {
                        srOutput.Close();
                        txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] No route to host." + Environment.NewLine + txtOutput.Text;
                        MessageBox.Show("No route to host.");
                        niApp.Icon = new System.Drawing.Icon(@"icon_disconnect.ico");
                        return false;
                    }

                }
                srOutput.Close();
                txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Login passed." + Environment.NewLine + txtOutput.Text;
                niApp.Icon = new System.Drawing.Icon(@"icon_connect.ico");
                return true;
            }
            catch { txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Troubles running file \"wget.exe\"." + Environment.NewLine + txtOutput.Text; }
            return false;
        } //logins in to gozips

        private bool PingTest(string host) //pings a website for connectivity
        {
            /* Easy Ping
             * Date Created: 10/3/2006 7:22:41 PM
             * Original Author: Kelly S. Elias
             * URL: http://devdistrict.com/codedetails.aspx?A=396
             */
            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
            try
            {
                System.Net.NetworkInformation.PingReply reply = ping.Send(host, 10000);
                //MessageBox.Show("Address:" + reply.Address + "[Time: " + reply.RoundtripTime);
                return true;
            }
            catch { return false; }
        }

        private bool ValidUAIP()
        {
            string strhostname = System.Net.Dns.GetHostName();
            //string ipAddress = "No IP Address";
            //System.Net.Dns.GetHostAddresses(strhostname);
            bool HasUAnetIP = false;
            for(int x = 0; x < System.Net.Dns.GetHostAddresses(strhostname).Length; x++)
            {
                if (System.Net.Dns.GetHostAddresses(strhostname)[x].ToString().Contains("130.101."))
                {
                    HasUAnetIP = true;
                }
            }
            //if (!HasUAnetIP)
            //{
            //    //change to ok/cancel or yes/no box to allow override
            //    MessageBox.Show("Warning!! You do not appear to have UA network assigned IP address!");
            //}
            return HasUAnetIP;

        }

        private string GetAllIPAddresses()
        {
            string strAllIPs="";
            string strHostName = System.Net.Dns.GetHostName();
            for (int x = 0; x < System.Net.Dns.GetHostAddresses(strHostName).Length; x++)
                //if (System.Net.Dns.GetHostAddresses(strHostName)[x].ToString()!="127.0.0.1") //exclude localhost
                    strAllIPs += "IP:" + System.Net.Dns.GetHostAddresses(strHostName)[x].ToString() + "[";
            return strAllIPs;
           
        }

        private void btnDetails_Click(object sender, EventArgs e)
        {
            if (btnDetails.Text == "<< Less") //grow form
            {
                Form1.ActiveForm.Height = 142;
                btnDetails.Text = "Details >>";
            }
            else
            {
                Form1.ActiveForm.Height = 241;
                btnDetails.Text = "<< Less";
            }

        }

        private void niApp_DoubleClick(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
                Hide();
        }

        private void tmrAttempt_Tick(object sender, EventArgs e)
        {
            niApp.Text = GetAllIPAddresses(); //update known IP addresses
            if (PingTest("www.uakron.edu"))
            {
                if (!WebTest("www.google.com"))
                {
                    if (Login(txtUsername.Text, txtPassword.Text))
                        txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Reconnected automatically." + Environment.NewLine + txtOutput.Text;
                    else
                        MessageBox.Show("Ran but didn't authenicate. Check username / password.");
                }
                else
                    txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] No disconnect detected." + Environment.NewLine + txtOutput.Text; ;
            }
        }

        private bool WebTest(string site)
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = "wget.exe";
            proc.StartInfo.Arguments = site + " -o webtest.log --spider --no-check-certificate";
            proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            try
            {
                proc.Start();
                proc.WaitForExit(); //this keeps it from reading the previous log of wget.
                StreamReader srOutput = File.OpenText("webtest.log");
                string read = null;
                while ((read = srOutput.ReadLine()) != null)
                {
                    //txtOutput.Text += read;
                    if (read.Contains("connected."))
                    {
                        srOutput.Close();
                        //MessageBox.Show("connected Online.");
                        return true;
                    }
                }
                srOutput.Close();
                //MessageBox.Show("Disconnected.");
                niApp.Icon = new System.Drawing.Icon(@"icon_disconnect.ico"); 
                return false;
            }
            catch
            {
                MessageBox.Show("Unknown error in WebTest Fill out a bug report http://code.google.com/p/uakron-dormlogin/issues/entry.");
                return false;
            }
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {

            if (WebTest("https://gozips.uakron.edu/zid/disconnect.cgi"))
            {
                tmrAttempt.Enabled = false;
                tmrAttempt.Stop();
                txtOutput.Text = Environment.NewLine + "[" + DateTime.Now + "] Disconnected and autoreconnect feature turned off." + Environment.NewLine + txtOutput.Text; ;
                niApp.Icon = new System.Drawing.Icon(@"icon_disconnect.ico");
            }
            else
                MessageBox.Show("Could not disconnect.");
        }

        /*private void TroubleShoot()
        {
            //check for ip
            //ping gateway
                //determin gateway.
        }*/

        private void reLoginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Login(txtUsername.Text, txtPassword.Text);
        }
    }
}